'use strict'
import {
  Model,
  DataTypes,
  InferAttributes,
  InferCreationAttributes,
  CreationOptional,
  BelongsToManyAddAssociationsMixin,
} from 'sequelize'
import dayjs from 'dayjs'
import Category from './category'
import { Models } from '../type'
import AttributeAttributeValue from './attributeattributevalue'
import AttributeValue from './attributevalue'
import sequelize from '.'

class Attribute extends Model<InferAttributes<Attribute>, InferCreationAttributes<Attribute>> {
  declare id: CreationOptional<number>
  declare name: string
  declare categoryId: number
  declare createdAt: CreationOptional<Date>
  declare updatedAt: CreationOptional<Date>

  declare addAttributes: BelongsToManyAddAssociationsMixin<AttributeValue, 'attributeId'>

  static associate(models: Models) {
    Attribute.belongsTo(models.Category, { as: 'category', foreignKey: 'categoryId' })
    Attribute.belongsToMany(models.AttributeValue, {
      through: AttributeAttributeValue,
      foreignKey: 'attributeId',
      as: 'values',
    })
  }
}
Attribute.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {
          msg: '属性名称必须填写。',
        },
        notEmpty: {
          msg: '属性名称不能为空。',
        },
        len: {
          args: [2, 45],
          msg: '属性名称长度必须在2~45个字符之间。',
        },
      },
    },
    categoryId: {
      type: DataTypes.INTEGER,
      // allowNull: false,
      // validate: {
      //   notNull: {
      //     msg: '分类ID必须填写。',
      //   },
      //   notEmpty: {
      //     msg: '分类ID不能为空。',
      //   },
      //   async isPresent(value: number) {
      //     const category = await Category.findByPk(value)
      //     if (!category) {
      //       throw new Error(`ID为:${value}的分类不存在。`)
      //     }
      //   },
      // },
    },
    createdAt: {
      type: DataTypes.DATE,
      get() {
        return this.getDataValue('createdAt')
          ? dayjs(this.getDataValue('createdAt')).format('YYYY-MM-DD HH:mm:ss')
          : null
      },
    },
    updatedAt: {
      type: DataTypes.DATE,
      get() {
        return this.getDataValue('updatedAt')
          ? dayjs(this.getDataValue('updatedAt')).format('YYYY-MM-DD HH:mm:ss')
          : null
      },
    },
  },
  {
    sequelize,
    modelName: 'Attribute',
  },
)

export default Attribute
